//
//  ViewController.swift
//  StringForSwift
//
//  Created by DeLongYang on 2017/7/24.
//  Copyright © 2017年 YiXue. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    
    var radarView:AATRaderView = AATRaderView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
//        stringOutPut()
//        //
//        createString()
//        //
//        calulateString()
//        //
//        cutOutString()
        //
//        spliceString()
//        compareString()
//        bigLowercase()
//        stringChange()
        
        //  componet string
//          componentStringIndex()
//        stringInsert()
//        stringDelete()
          stringReplace()
        let rect = CGRect(x: 60, y: 100, width: 300, height: 300)
        radarView = AATRaderView(frame:rect )
        radarView.backgroundColor = UIColor.white
        view.addSubview(radarView)
        
        radarView.startScan()
    }

    // 多加 一个星星
    @IBAction func addOneMoreBtnClick(_ sender: Any)
    {
        radarView.showOneMoreStarView()
    }
    

    //
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // string  output
    func stringOutPut() {
        let num:Int = 123
        print(num)
        print("\(num)")
        print(String(num))
    }
    
    // string create
    func createString() {
        // 和C  和 OC 中不同的是  指定 Character 类型 使用 "" 引号
//        let char:Character = "I"
        
        
        let str3 = "I Love China"
        let str5 = str3                  // 是 指针赋值
        let str6 = String(str3)         //  是值赋值

//       UnsafeMutablePointer(Unmanaged<AnyObject>.passUnretained(str3 as AnyObject))
        
        let str3P = Unmanaged<AnyObject>.passUnretained(str3 as AnyObject)
        let str5P = Unmanaged<AnyObject>.passUnretained(str5 as AnyObject)
        let str6P = Unmanaged<AnyObject>.passUnretained(str6 as AnyObject)
        
//        print("\(String(describing: str3P)) --- \(String(describing: str5P)) ---\(String(describing: str6P))")
        // 从运行的内存中就可以看出来 
        
        
        var str7 = "I live in China"
        var str8 = str7
        
        str7 = "you can you up"  // 同样的地址
        print("\(str7)  --- \(str8)")  // you can you up  --- I live in China

        // 输出 后 str7  有了新的地址  而 str8 还是原来的地址  str8 并没有和 str7 一样
        let str9 = NSString(format: "age is %d score is %d",18,20)
        let str10 = NSString(cString: "这是一个C字符串", encoding: String.Encoding.utf8.rawValue)
        let str11 = NSString(utf8String: "这是一个C转换过来的");
        
        // 从文件创建  沙盒 目录下并没有这个文件 则返回nil 值
        let path = NSHomeDirectory() + "/Desktop/test.RTF"
        let str12 = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue)
//        print(str12)
        
        // 通过 URL 创建
        let url = NSURL(fileURLWithPath: path)
        let str13 = try?NSString(contentsOf: url as URL, encoding: String.Encoding.utf8.rawValue)
        print(str13)
    }
    
    // string length calculate 
    func calulateString() {
        // 我们测试 空格 是否 也算一个 count
        let str1:String = "this_is a String"
        let num1:Int = str1.characters.count
        print("\(num1)")
    }
    
    // cut out string 
    func cutOutString() {
        let cutString:String = "Bei Jing Ni Hao 你好"
        
        let startIndex = cutString.startIndex
        let endIndex = cutString.endIndex
        
        // 笔者 认为 如果 传 -2 等进去就是往前 如果 数值的范围超出 是否会 造成 问题闪退啥的？ 确实会产生闪退
        // 在OC 中有这种情况
        let index = cutString.index(startIndex, offsetBy: 2)
        print(index)
        let range = cutString.index(startIndex, offsetBy: 1)...cutString.index(startIndex, offsetBy: 4)
        print(range)
        
        // 测试。index2  如果超出范围 就会出现crash
//        let index2 = cutString.index(startIndex, offsetBy: -3);
//        print(index2)
        
        let index3 = cutString.index(endIndex, offsetBy: -4);
//        let subString = cutString.s
        print(cutString[index3])
        
        // 其实 在这里 String.Index 就是 range 的意思 可以 加减 然后传进去。和 OC 的不同
        print(cutString[range])
        //
//        let rangeString = cutString.substring(with: )
        
    }
    
    //  splice string
    func spliceString() {
        let str1 = "bei"
        let str2 = "Jing"
        var str3 = str1 + str2
        
//        str1.appending("dddd")
        // 在末尾 添加 13333
        str3.write("13333")
        let str4 = str1.appending("de long")  // this two method is equal
        
        // space was also included into the string
        let str5 = str1.appendingFormat("jing name:  %d %d", 13,23)
        print(str5)
        
        // to ajust OC  String we can asing let nsmutableString
        let str6:NSMutableString = "Bei Jing"
        str6.appending("Hello ")
        
        
    }
    // compare string 
    func compareString() {
        let str1:String = "bei Jing"
        let str2:String = "bei Jing"
        let bll:Bool = str1==str2
        
        let str3:String = "Bei Jing";
        let bll2:Bool = str1==str3;
        
        // String 重载了 = 运算符 这样可以不用使用isEqual了
        let b3 = str1.hasPrefix("be")
        let b4 = str1.hasSuffix("ng")
        
        //
        let b5 = str1.isEmpty
        let b6:ComparisonResult = str1.compare(str2)  // 0
        let b7 = str1.caseInsensitiveCompare(str3).rawValue
        let b8 = str1.compare(str3).rawValue
        
        //
    
        
    }
    
    //  this is a improve
    func bigLowercase() {
        //
        let str1 = "bei Jing Welcome"
        let str2 = str1.lowercased()
        let str3 = str1.uppercased()
        
        //  首字母大写 如果之前 那个 b 就没有
        let str4 = str1.capitalized
        print(str4)
    }
    
    //  string change  transfer
    func stringChange(){
        
        // charactet and  number
        let ch:Character = "A"
        var charIntValue = 0;
        for charStr in String(ch).unicodeScalars{
            charIntValue = Int(charStr.value)
        }
        print(charIntValue)  // character -> int
        
        let intva = 65
        let characterFromInt = Character(UnicodeScalar(intva)!);
        print(characterFromInt)  // int -> charcter
        
        // string and int
        let intString = "64"
        let intValue:Int? = Int(intString)
        print(intValue)     // string -> int 
        
        // 数字 转 字符串
        
        // Int 型数字 转 字符串
        let intVal3:Int = 123;              let intStr1:String = intVal3.description
        
        // Int32 型数字 转 字符串
        let int32Val1:Int32 = 32;           let int32Str1:String = int32Val1.description
        
        // Int64 型数字 转 字符串
        let int64Val1:Int64 = 64;           let int64Str1:String = int64Val1.description
        
        // Float 型数字转 字符串
        let floatVal1:Float = 2.1;          let floatStr1:String = floatVal1.description
        
        // Double 型数字转 字符串
        let doubleVal1:Double = 162.1;      let doubleStr1:String = doubleVal1.description
        
        // Bool 型 转 字符串
        let boolVal1:Bool = true;           let boolStr1:String = boolVal1.description
        
        //
        // NSString 型字符串
        // 字符串 转 数字
        // 字符串 转 Int 型数字
        let intVal4:Int = NSString(string: "6432").integerValue
        
        // 字符串 转 Int32 型数字
        let int32Val2:Int32 = NSString(string: "32").intValue
        
        // 字符串 转 Int64 型数字
        let int64Val2:Int64 = NSString(string: "64").longLongValue
        
        // 字符串 转 Float 型数字
        let floatVal2:Float = NSString(string: "2.1").floatValue
        
        // 字符串 转 Double 型数字
        let doubleVal2:Double = NSString(string: "162.1").doubleValue
        
        // 字符串 转 Bool 型
        let boolVal2:Bool = NSString(string: "false").boolValue
        
        // 这个很有意思 162.1  会被转换成 162.099999999999
        let boolVa1111 = NSString(string:"new").boolValue  // false
        
        let boolVa1112 = NSString(string:"tru").boolValue  // true
        let boolVa1113 = NSString(string:"tr").boolValue  // true
        let boolVa1114 = NSString(string:"t").boolValue  // true
        let boolVa1115 = NSString(string:"ABC").boolValue  // false
        let boolVa1116 = NSString(string:"true").boolValue  // false  这是一个有意思的地方
        // 我们设置。t 居然也是 true。不是 false
    }
    
    // subString expriment 
    func stringSub() {
        let str1:NSString = "bei jing nin hao nin hao";
        let str2:String = "nin";
        
        let range = str1.range(of: str2)
        if range.location != NSNotFound  {
            print("foundString")
        }
        
        // 条件查找
        /*
         CaseInsensitiveSearch = 1,               // “A”等同于“a”，不分大小写查找
         LiteralSearch = 2,                       // Unicode 的点对点比较。它只在所有字符都用相同的方式组成的情况下才会返回相等。
         BackwardsSearch = 4,                     // 在字符串的末尾开始反向搜索
         AnchoredSearch = 8,                      // 只考虑搜索的起始点（单独使用）或终止点（当与 NSBackwardsSearch 结合使用时）。
         // 这个方法可以用来检查前缀或者后缀，以及大小写不敏感（case-insensitive）或者
         // 音调不敏感（diacritic-insensitive）的比较。
         
         NumericSearch = 64,                      // 它对字符串里的数字排序
         
         DiacriticInsensitiveSearch = 128,        // “A” 等同于 “Å” 等同于 “Ä.”
         WidthInsensitiveSearch = 256,            // 一些东亚文字（平假名和片假名）有全宽与半宽两种形式
         ForcedOrderingSearch = 512,
         RegularExpressionSearch = 1024           // 使用正则表达式搜索
         */
        
        // 从后往前查找，找到第一个即停止查找 这个挺有意思的
        let range2 = str1.range(of: str2, options: NSString.CompareOptions.backwards)
        
        range2.location == NSNotFound ? print("not found") : print(range2)
        
        // 范围内查找
        
        // 在某个范围内查找  insensitive    不区分大小写
        let range3 = str1.range(of: str2,
                                        options: NSString.CompareOptions.caseInsensitive,
                                        range: NSMakeRange(8, 10))
        
        range3.location == NSNotFound ? print("not found") : print(range3)
        
    }
    
    //  sub index subString 
    func componentStringIndex() {
        let str1:String = "chen$chao$ni$hao$ma"
        let str2:String = "bei$jing#ni@hao&ma"
        
        let characterSet:CharacterSet = CharacterSet(charactersIn: "#$@&") // 这样就方便很多了
        let arr1 = str1.components(separatedBy: "$")
        let arr2 = str2.components(separatedBy: characterSet)  //  按照字符集合 分解  也就是 即使是set 中的任意一个都会分解 成相应的字符串
        print(arr1)
        print(arr2)
        let str5:NSString = "Users/JHQ0228/Desktop"
        let arr5 = str5.pathComponents; // 自动按照 路径来分解 这个字符串
    
        //
    }
    
    // string insert
    func stringInsert() {
        // 
        var str1:String = "bei Jing Huan Ying NI"
        str1.insert("!", at: str1.startIndex)
        print(str1)
        str1.insert(contentsOf: "huan ".characters, at: str1.startIndex)
        print(str1)
        
        var str2:NSMutableString = "bei jing huan ying ni"
        str2.setString("ni jing  zhe she set string ")
        print(str2)
    }
    
    // string delete
    func stringDelete() {
        var str1:String = "bei jing huan ying ni!"
//        let index = str1.endIndex
//        str1.remove(at: str1.endIndex)  // 直接报错  can not from a Character from a emoty string
        print(str1)
        
        // 但是 startIndex。确实可以的
        str1.remove(at: str1.startIndex)
        
        //
       
        str1.remove(at: str1.index(str1.startIndex, offsetBy: 2))
        print(str1)
        //
        str1.remove(at: str1.index(before: str1.endIndex))
        print(str1)
        
        //  可以使用 before 和 after。不能用 end  remove 之前
        let range = str1.index(str1.startIndex, offsetBy: 2)...str1.index(str1.endIndex, offsetBy: -1);
        str1.removeSubrange(range);
        
        // startIndex  和 endIndex 不同的是 endIndex 是换行符 所以 -1 endIndex 才到之后一个字符
        
    }
    
    // string replace   字符串替换
    func stringReplace(){
        
        // apple 的API 解释清楚了 这个range 的设置
        var str1:String = "bei jing huan ying nin !";
        let range = str1.index(str1.startIndex, offsetBy: 2)...str1.index(str1.endIndex, offsetBy: -1);
        
        let range2 = str1.index(str1.startIndex, offsetBy: 2)..<str1.index(str1.endIndex, offsetBy: -1)
        var str2 = str1.replacingCharacters(in: range2, with: "YANG")
        print(str2)
        
    }
    
}

































